<?php
  require_once("../includes/config.php"); 
  if($_SERVER["REQUEST_METHOD"] == "POST")
  {
	$error = 0; //indicates no error
    $apartments_otherContracts = ""; 
    
    if(isset($_POST['fixed_discount']))
      $fixed_discount  = $_POST['fixed_discount'];
    else
      $fixed_discount = 0;
      
    
    $from = $_POST['from'];
    $to = $_POST['to'];
    
    //compare out date of this contracts with upcoming contracts on the same apartment
    $out_ts = strtotime($to);
    $in_ts = strtotime($from);
    
    //check to see if chosen apartments has other contracts cover the chosen period or not
    $apartments = explode("|", $_POST['apartment_id']);
    foreach($apartments as $apartment_id)
    {
      
      $contracts_p = query("SELECT * FROM contract_apartments where apartment_id = ? ",$apartment_id);
      foreach($contracts_p as $contract_p)
      {
        $contract = query("SELECT * FROM contracts WHERE contract_id = ?",$contract_p['contract_id']);
        if(empty($contract))
		{
			continue;
		}
		else
		{
			$contract = $contract[0];
		}
		
        if($contract['contract_status'] == 3)
        {
          continue;
        }
        else
        {
          
          $contract_in_ts = strtotime($contract['mildai_from']);
          $contract_out_ts = strtotime($contract['miladi_out']);
		  if($_POST['what-button'] == 2) // if check in is requested
		  {
			$apartment = query("SELECT status FROM apartments WHERE id = ?",$apartment_id);
			$condition = (($out_ts <= $contract_in_ts || $in_ts >= $contract_out_ts) &&  $apartment[0]['status'] != 1); //checks the dates and ensures that apartment is not red which indicates that this apartment has clients in it
		  }
		  else //if booking is requested
		  {
			$condition = ($out_ts <= $contract_in_ts || $in_ts >= $contract_out_ts);
		  }
          if($condition)
          {
            //KEEP Going
          }
          else
          {
            $error = 1; //indicates that there's a contract on the chosen apartment during this period
            //get $apartment name
            $apartment = query("SELECT apart_name FROM apartments WHERE id = ?",$apartment_id);
            $apartments_otherContracts .= $apartment[0]['apart_name']." ";
            break;
          }
        }
		
      }
	  if($error == 1)
		break; //break of outer loop as well
      
    }
    
    if($error == 1)
    {
      $message =  " فترة العقد المختارة غير مناسبة لوجود عقود أو حجوزات فى نفس الفترة على الشقق، أو أن الشقة مؤجرة ولم يتم عمل خروج لها بعد انتهاء مدة الإيجار ".$apartments_otherContracts;
	  echo '-1|'.$message;
	  die();
    }
    
    else if(is_numeric($_POST['client_id']) &&  $_POST['client_id']> 0)
    {
	      //get Company Discount if set
      if(isset($_POST['company_id']) && !empty($_POST['company_id'])&&!isset($_POST["choose_method"]) )
      {
        $results = query("SELECT discount_for_company FROM companies WHERE company_id = ?",$_POST['company_id']);
        $discount_for_company = $results[0]['discount_for_company'];
      }
      else
        $discount_for_company = 0;
        
      $amount = round($_POST['final-price'],2); 
      $date = date('Y/m/d', time());
      $result = query("INSERT INTO contracts 
          (notes,client_id,apartment_name, period, rent_type, mildai_from,miladi_out ,hijri_in,hijri_out,total,discount,owner_id,related_company,chosen_weekly,chosen_daily,chosen_monthly,company_id,fixed_discount,created_at,user_id,co_discount) 
      VALUES 
          (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
          
      $_POST['notes'],$_POST['client_id'],$_POST['apart_name'],$_POST['period'],$_POST['rent_type'],$from,$to,$_POST['hijri-from'],$_POST['hijri-to'],$amount,$_POST['discount'],$_SESSION['user_id'],$_POST['company_name']
      ,$_POST['weekly_price'],$_POST['daily_price'],$_POST['monthly_price'],$_POST['company_id'],$fixed_discount,$date,$_SESSION['id'],$discount_for_company);
      
      $id = query("getlastid");
      //insert into contract_apartments contract id as well as apartments id (one to many relation)
            
      $_SESSION['recent_contract'] =  $id;
      
      if($_POST['what-button'] == 2)
      {
   		$status = 1;
		//update Contract Status
		$datee = date("Y-m-d h:i:s");
		$query = query("UPDATE contracts SET contract_status = 2, actual_in = ? WHERE contract_id = ?",$datee,$id);
		$client = query('SELECT mobile,name from clients where id = ?',$_POST['client_id']);
		$name = $client[0]['name'];
		$mobile =$client[0]['mobile'];
			  
			$message = "عزيزى /".$name . "\n
			بقلوب تملئها المحبة نقول لكم اهلا وسهلا ومرحبا بكم في لؤلؤة ليمار (غرف واجنحة فندقية ) ونتمنى لكم اقامة سعيدة وان تنال خدماتنا رضائكم . دخولكم يوم ".$_POST['from']." وخروجكم يوم ".  $_POST['to'] ." لمدة " . $_POST['period'] ." يوم. في حال طلب اي خدمة نأمل الاتصال بالاستقبال على التحويلة (صفر) او (100) علما بانه تتوفر خدمة الانترنت في جميع انحاء الفندق. نود لفت نظر سعادتكم بأن موعد الخروج Check Out المعتاد في الفندق هو الساعة الثانية ظهرا . رقم الفندق (920025725) ، فاكس: 6575959-012";
			$results = sendSMS($mobile, 'Lemar', utf8ToUnicode($message));
      }
      else
      {
        $status = 6;
        //update Contract Status
        $query = query("UPDATE contracts SET contract_status = 1 WHERE contract_id = ?",$id);
        
        $client = query('SELECT mobile,name from clients where id = ?',$_POST['client_id']);
        $name = $client[0]['name'];
        $mobile =$client[0]['mobile'];
        $price_discounted = $amount - (  ( ($_POST['discount'] + $discount_for_company) )  ) - $fixed_discount;

        $message = "عزيزى / ".$name . "\n

لؤلوة ليمار (غرف واجنحة فندقية) ترحب بكم وتتطلع دائما لخدمتكم. تم عمل حجز لكم بالمعلومات التالية: \n" . 
"دخولكم يوم ".  $_POST['from'] . " وخروجكم يوم ".  $_POST['to'] . " لمدة ". $_POST['period'] . "، إجمالى المبلغ المطلوب منكم هو ". $price_discounted." ريال سعودى. لتعديل الحجز او الاستفسار نأمل الاتصال على الرقم الموحد للفندق (920025725) ، فاكس 6575959-012.";  

       $results = sendSMS($mobile, 'Lemar', utf8ToUnicode($message));
      }
      
	  foreach($apartments as $apartment)
      {
		 
		//check to see if there's another client on the same apartments. if so, There's no need to change apartment status
		$contracts = query("SELECT * from contract_apartments LEFT JOIN contracts on contract_apartments.contract_id  = contracts.contract_id WHERE apartment_id = ? and contract_status = 2 ",$apartment);
		if(!empty($contracts) && $_POST['what-button'] == 2)
		{
			//Don't Change Apartment Status and proceed
		}
		else
		{
			//change apartment Status
			$currentApart = query("SELECT apart_name,status FROM apartments WHERE id=?",$apartment);
			$currentStatus = $currentApart[0]['status'];
			$currentname = $currentApart[0]['apart_name'];
			$result = query("UPDATE apartments SET status=? where id=?",$status,$apartment);
			$datee = date("Y-m-d h:i:s");
			$updateHistoryTable = query("INSERT INTO history (action,date_happened) VALUE (?,?)","Apartment {$currentname} changed from {$currentStatus} to {$status}",$datee);

		}
		
		//update contracts apartments table
		$result = query("INSERT INTO contract_apartments 
          (contract_id,apartment_id) 
        VALUES 
            (?,?)",
        $id,$apartment);
		
      }
            $_SESSION['success_message_pop'] = "تم إضافة العقد بنجاح"; 

        
            //if the request came from apartments, redirect back to apartments.php
      if($_POST['requsting-page'] == 1)
        echo "1";//redirect("apartments.php");   
      else
        echo "2";//redirect("bookings.php");   
      
    }
    else
    {
      $message =  "هناك مشكلة فى عمل العقد";
      echo "-2|".$message;
	  die();
    }

 }
	?>